package weekMatch.two_103;

import mess.AddTwoNumbers;

import java.util.*;

public class LeeCode_04 {
    public static void main(String[] args) {
//        System.out.println(countOperationsToEmptyArray2(new int[]{3, 4, -1}));
        System.out.println(countOperationsToEmptyArray2(new int[]{-15, -19, 5}));
    }
    private static long countOperationsToEmptyArray2(int[] nums) {
        LinkedList<Integer> list = new LinkedList<>();
        for (int num : nums) {
            list.add(num);
        }
        int n = nums.length;
        Arrays.sort(nums);
        int index = 0;
        int ans = 0;
        while (index < n){
            int min = nums[index++];
            int i = 0;
            for (Integer num : list) {
                if (num == min){
                    break;
                }
                i++;
            }
            List<Integer> list1 = list.subList(0, i);
            List<Integer> list2 = list.subList(i + 1, list.size());
            list2.addAll(list1);
            list = new LinkedList<>(list2);
            ans += i + 1;
        }
        return ans;
    }
    private static long countOperationsToEmptyArray(int[] nums) {
        TreeSet<Integer> set = new TreeSet<>();
        int n = nums.length;
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < n; i++) {
            int num = nums[i];
            set.add(num);
            map.put(num, i);
        }
        int len = n;
        int ans = 0;
        while (!set.isEmpty()){
            int min = set.first();
            set.pollFirst();
            int index = map.get(min);
            int rl = len - 1 - index;
            ans += index + 1;
            map.remove(min);
            for (Integer num : set) {
                if (map.get(num) < index){
                    map.put(num, map.get(num) + rl);
                }else {
                    map.put(num, map.get(num) - index - 1);
                }
            }
            len--;
        }
        return ans;
    }
}
